package com.sunny.ynhz.api;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.sunny.ynhz.api.retrofitUtil.ResponseConverterFactory;
import com.sunny.ynhz.utils.MD5Utils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Administrator on 2016-10-11.
 */
public class HttpManager {
    private final Retrofit retrofit;
    public static ApiService apiService;
    private volatile static HttpManager INSTANCE;
    String baseUrl = NetUrl.baseUrl;

    private HttpManager() {


        OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor).build();
        ScalarsConverterFactory scalarsConverterFactory = ScalarsConverterFactory.create();
        retrofit = new Retrofit.Builder()
                .addConverterFactory(ResponseConverterFactory.create()).addConverterFactory(GsonConverterFactory.create(new Gson()))
                .addConverterFactory(scalarsConverterFactory)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(defaultHttpClient)
                .baseUrl(baseUrl)
                .build();
        apiService = retrofit.create(ApiService.class);
    }

    /**
     * 创建单例
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    public static ApiService getInstance() {
        if (INSTANCE == null) {
            synchronized (HttpManager.class) {
                INSTANCE = new HttpManager();
            }
        }
        return INSTANCE.apiService;
    }

    //拦截器，添加缓存，添加header统一参数
    //MD5（用户ID+MD5（时间戳X5-1799））  token生成规则
    static Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            String cacheControl = request.cacheControl().toString();
            if (TextUtils.isEmpty(cacheControl)) {
                cacheControl = "public, max-age=60";
            }
            return response.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .addHeader("token", MD5Utils.string2MD5((System.currentTimeMillis() * 5 - 1799) + ""))
                    .addHeader("tokentime", System.currentTimeMillis() + "")
                    .removeHeader("Pragma")
                    .build();
        }
    };
}
